// 检查图片链接可用性
const https = require('https');
const fs = require('fs');

// 从serviceManager云函数中提取所有图片链接
const extractImageLinks = () => {
  const serviceManagerPath = './cloudfunctions/serviceManager/index.js';
  const content = fs.readFileSync(serviceManagerPath, 'utf8');
  
  // 使用正则表达式提取所有Unsplash图片链接
  const imageRegex = /https:\/\/images\.unsplash\.com\/photo-[^'"\s]+/g;
  const matches = content.match(imageRegex) || [];
  
  // 去重
  const uniqueLinks = [...new Set(matches)];
  
  return uniqueLinks;
};

// 检查单个图片链接是否可用
const checkImageLink = (url) => {
  return new Promise((resolve) => {
    const request = https.get(url, (response) => {
      resolve({
        url,
        status: response.statusCode,
        success: response.statusCode === 200
      });
    });

    request.on('error', (error) => {
      resolve({
        url,
        status: 'ERROR',
        success: false,
        error: error.message
      });
    });

    request.setTimeout(10000, () => {
      request.destroy();
      resolve({
        url,
        status: 'TIMEOUT',
        success: false,
        error: 'Request timeout'
      });
    });
  });
};

// 批量检查所有图片链接
const checkAllImages = async () => {
  console.log('🔍 开始检查图片链接可用性...\n');
  
  const imageLinks = extractImageLinks();
  console.log(`发现 ${imageLinks.length} 个唯一的图片链接\n`);
  
  const results = [];
  
  for (let i = 0; i < imageLinks.length; i++) {
    const url = imageLinks[i];
    console.log(`检查 ${i + 1}/${imageLinks.length}: ${url}`);
    
    const result = await checkImageLink(url);
    results.push(result);
    
    if (result.success) {
      console.log('✅ 可用');
    } else {
      console.log(`❌ 失效 (${result.status})`);
    }
  }
  
  console.log('\n' + '='.repeat(60));
  console.log('📊 检查结果汇总:\n');
  
  const successCount = results.filter(r => r.success).length;
  const failCount = results.filter(r => !r.success).length;
  
  console.log(`✅ 可用链接: ${successCount}`);
  console.log(`❌ 失效链接: ${failCount}`);
  
  if (failCount > 0) {
    console.log('\n🚨 失效的图片链接:');
    results.filter(r => !r.success).forEach((result, index) => {
      console.log(`${index + 1}. ${result.url}`);
      console.log(`   状态: ${result.status}`);
      if (result.error) {
        console.log(`   错误: ${result.error}`);
      }
      console.log('');
    });
    
    // 为失效链接推荐替代方案
    console.log('💡 推荐的替代图片链接:');
    const alternatives = [
      'https://images.unsplash.com/photo-1581092160562-40aa08e78837?w=400&h=300&fit=crop', // IT设备
      'https://images.unsplash.com/photo-1544197150-b99a580bb7a8?w=400&h=300&fit=crop', // 网络设备
      'https://images.unsplash.com/photo-1558494949-ef010cbdcc31?w=400&h=300&fit=crop', // 商业设备
      'https://images.unsplash.com/photo-1563013544-824ae1b704d3?w=400&h=300&fit=crop', // 技术设备
      'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=400&h=300&fit=crop', // 办公技术
      'https://images.unsplash.com/photo-1556742049-0cfed4f6a45d?w=400&h=300&fit=crop', // 收银系统
    ];
    
    results.filter(r => !r.success).forEach((result, index) => {
      const altIndex = index % alternatives.length;
      console.log(`${index + 1}. 替换 ${result.url}`);
      console.log(`   推荐: ${alternatives[altIndex]}\n`);
    });
  }
  
  console.log('🎉 图片链接检查完成!');
  
  return results;
};

// 运行检查
checkAllImages().catch(console.error); 